<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit">
        <a-divider orientation="left">微信公众号推荐海报设置</a-divider>
        <a-form-item
          label="上传海报"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          extra="请注意海报尺寸"
        >
          <a-upload
            name="iFile"
            accept="image/*"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="onUpload"
            :before-upload="beforeUpload"
            :multiple="true"
          >
            <img class="prew-poster" v-if="imageUrl" :src="imageUrl" alt="海报" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
          label="海报链接"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input-search
            v-clipboard:copy="record.posterUrl"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            v-decorator="[`posterUrl`]"
          >
            <a-button slot="enterButton">
              复制
            </a-button>
          </a-input-search>
        </a-form-item>
        <a-divider v-if="imageUrl" orientation="left">效果图预览</a-divider>
        <div v-if="imageUrl" class="prew-show">
          <img :src="imageUrl">
        </div>
        <a-form-item :wrapper-col="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import * as Api from '@/api/setting/store'
import { isEmpty } from '@/utils/util'
import { image } from '@/api/upload'

export default {
  data () {
    return {
      // 当前设置项的key
      key: 'poster',
      // 标签布局属性
      labelCol: { span: 3 },
      // 输入框布局属性
      wrapperCol: { span: 10 },
      // loading状态
      isLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录详情
      record: {},
      loading: false,
      imageUrl: '',
      // 上传中的文件
      uploading: []
    }
  },
  // 初始化数据
  created () {
    // 获取当前详情记录
    this.getDetail()
  },
  methods: {
    onCopy (e) {
      this.$message.success('内容已复制到剪切板！')
    },
    onError (e) {
      this.$message.error('抱歉，复制失败！')
    },
    onUpload (info) {
      const that = this
      this.loading = true
      // 记录上传状态
      this.uploading.push(true)
      const beforeUploadCount = this.uploading.length
      // 构建上传参数
      var formData = new FormData()
      formData.append('iFile', info.file)
      formData.append('groupId', 0)
      // 开始上传
      image(formData)
        .then(result => {
          setTimeout(() => {
            if (beforeUploadCount === this.uploading.length) {
              this.uploading = []
              that.imageUrl = result.data.fileInfo.external_url
              // 设置表单字段posterUrl
              that.form.setFieldsValue({ posterUrl: that.imageUrl })
              this.$message.success(result.message)
              this.loading = false
            }
          }, 10)
        })
        .catch(() => {
          this.loading = false
        })
    },
    beforeUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 10
      if (!isLt1M) {
        this.$message.error('文件大小不能超出10MB')
        return false
      }
      return true
    },
    // 获取当前详情记录
    getDetail () {
      this.isLoading = true
      Api.detail(this.key)
        .then(result => {
          // 当前记录
          this.record = result.data.values
          // 设置默认值
          this.setFieldsValue()
        })
        .finally(result => {
          this.isLoading = false
        })
    },

    /**
     * 设置默认值
     */
    setFieldsValue () {
      const { record, $nextTick, form } = this
      const that = this
      !isEmpty(form.getFieldsValue()) && $nextTick(() => {
        that.imageUrl = record.posterUrl
        form.setFieldsValue(pick(record, ['posterUrl']))
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.isLoading = true
      Api.update(this.key, { form: values })
        .then((result) => {
          // 显示提示信息
          this.$message.success(result.message, 1.5)
        })
        .finally((result) => {
          this.isLoading = false
        })
    }

  }
}
</script>
<style lang="less" scoped>
/deep/.ant-form-item-control {
  padding-left: 10px;

  .ant-form-item-control {
    padding-left: 0;
  }
}
.ant-divider {
  margin-top: 50px !important;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.prew-poster{width: 100%}
.prew-show{width: 100%;margin-left: 14%;margin-bottom: 6%;}
.prew-show img{width: 50%;}
</style>
